package com.english.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.english.common.BiliBiliPageProcessor;
import com.english.domain.LText;
import com.english.common.TextsProcessor;
import com.english.common.VideoList;
import com.english.domain.Text;
import com.english.mappers.RecordMapper;
import com.english.mappers.TextMapper;
import com.english.service.ResourceService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ResourceServiceImp implements ResourceService {
    @Resource
    TextMapper textMapper;
    @Resource
    RecordMapper recordMapper;
    private String videoUrl = "https://search.bilibili.com/all?keyword=%E8%8B%B1%E8%AF%AD%E9%98%85%E8%AF%BB&from_source=webtop_search&spm_id_from=333.1007&search_source=3&duration=1";
    //返回文章的标题图片
    private String textsUrl = "https://apiv3.shanbay.com/news/retrieve/articles?ipp=10&page=1";
    private String textContentUrl = "https://apiv3.shanbay.com/news/articles/   {id}   ?source=1";

    @Override
    @Transactional
    public VideoList getVideo() {
        BiliBiliPageProcessor biliBiliPageProcessor = new BiliBiliPageProcessor(this.videoUrl);
        return new VideoList(biliBiliPageProcessor.getVideoHrefList(), biliBiliPageProcessor.getTextHrefList());
    }

    @Override
    public List<LText> getTextList() {
        TextsProcessor textsProcessor = new TextsProcessor(this.textsUrl);
        List<Text> textList = textsProcessor.getTextList();
        if (textList == null)return null;
        List<LText> lTextList = new ArrayList<>();
        //爬取到的text需要存入数据库。
        for (Text text : textList){
            LText lText = new LText(text);
            lTextList.add(lText);
            //text已存在不存入数据库
            if ( getTextById(text.getId()) == null){
                textMapper.insert(text);
            }
        }
        return lTextList;
    }

    @Override
    public Text getTextById(String id) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("id", id);
        return textMapper.selectOne(qw);
    }

    @Override
    public LText getLTextById(String id) {
        Text text = getTextById(id);
        LText lText = new LText(text);
        lText.setContentList(text.getContent());
        return lText;
    }

}
